package com.econ.powercloud.ems.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Spring EL工具
 *
 * @author chenxiaoqi
 * @since 2021/10/19
 **/
@Slf4j
public class ExpressionUtils {

    private ExpressionUtils() {
    }

    public static String parse(String expr, Map<String, Object> params) {
        String result = null;
        try {
            ExpressionParser parser = new SpelExpressionParser();
            Expression expression = parser.parseExpression(expr);
            EvaluationContext context = new StandardEvaluationContext();
            if (params != null) {
                params.keySet().forEach(key -> context.setVariable(key, params.get(key)));
            }
            result = expression.getValue(context, String.class);
        } catch (Exception e) {
            log.warn("表达式异常: " + expr, e);
        }
        return result;
    }

    public static String parse(String expr, Object[] args) {
        Map<String, Object> params = new HashMap<>();
        params.put("args", args);
        return parse(expr, params);
    }
}
